package com.yifeng.repo.base.utils.file;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;

/**
 * 写入数据到属性文件
 * @author lijing
 * @since 2023-05-15
 *
 */
public class PropertyUtils {
      
    /**  
    * 更新（或插入）一对properties信息(主键及其键值)  
    * 如果该主键已经存在，更新该主键的值；  
    * 如果该主键不存在，则插件一对键值。  
    * @param keyname 键名  
    * @param keyvalue 键值  
    */   
    public static boolean writeProperties(String profilePath,Map<String,Object> values) {          
        if(Objects.isNull(values) || values.isEmpty()) {
        	return false;
        }
    	try {   
        	Properties props = new Properties();
        	props.load(new FileInputStream(profilePath)); 
            OutputStream fos = new FileOutputStream(profilePath); 
            values.forEach((k, v) -> props.setProperty(k, String.valueOf(v)));   
            props.store(fos, "write properties value");   
        } catch (Exception e) {
        	throw new RuntimeException("属性文件更新错误");
        }   
    	return true;
    }   
    
    /**
     * 将json数据写入文件
     * @param profilePath 文件路径
     * @param data json数据
     * @return true:成功 false:失败
     */
    public static boolean writeJson(String profilePath,Object data) {
    	if(Objects.isNull(data)) {
        	return false;
        }
    	try {   
    		ObjectMapper mapper = new ObjectMapper();
        	String jsonData = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
    		FileOutputStream fileOutputStream=new FileOutputStream(profilePath);//实例化FileOutputStream
            OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream,"utf-8");//将字符流转换为字节流
            BufferedWriter bufferedWriter= new BufferedWriter(outputStreamWriter);//创建字符缓冲输出流对象
            bufferedWriter.write(jsonData);//将json数据写入文件
            bufferedWriter.flush();//清空缓冲区，强制输出数据
            bufferedWriter.close();//关闭输出流   
        } catch (Exception e) {
        	throw new RuntimeException("json文件更新错误",e);
        }   
    	return true;
    }   
  
}
